import React from 'react';
import ReactDOM from 'react-dom';
import mirror, {actions, connect,Link} from 'mirrorx';
import { FormattedMessage} from 'react-intl';
import { List, InputItem, Button } from 'antd-mobile';

function PwdModal ({cancel,getPwd,show,submitPassword}){
		const Lang = window.LangMessage ||{};
      
		return<div>
			{show && 
					<div className="confirmBox layer-mask">
						<div className="wrap">
							<List>
								<InputItem 	
									type="password"
									clear
									placeholder={Lang.input_transac_pwd ||  "请输入交易密码"}
									maxLength={6}
									onBlur={getPwd.bind(this)}
								><FormattedMessage id='transac_pwd' defaultMessage='交易密码'/></InputItem>
							</List>
							<div className="buttonWrap">
							<Button type="ghost" inline style={{ marginRight: '4px' }} className="am-button-borderfix" onClick={cancel}>Cancel</Button>
							<Button type="primary" inline style={{ marginRight: '4px' }} onClick={submitPassword}>Submit</Button>
							</div>
						</div>
					</div>
				}
			</div>
}


class App extends React.Component { 
	constructor(props) {
		super(props);        
        this.state={
            timeText:"",
            paying:false,
            orderDetail:{
                
            },
            pwd:'',
            show:false,
            payFailure:false
        }
        this.orderNo = T.urlQuery("id");
	}

	componentDidMount(){
        this.handleTime();
        
        this.requestOrderDetail();
    }
    componentWillUnmount(){
        clearInterval(this.interval);
    }

    handleTime =()=>{
        const orderDetail = this.state.orderDetail ||{};

        //let createTime = + new Date(orderDetail.createTime);
        let time = 30*60;   //(30 *60)  - Math.round((+new Date() - createTime)/1000);
        if(time<=0){
            //alert("The order has expired.");
        }else{
            this.showTime(time);
            this.interval = setInterval(()=>{
                time= time-1;
                this.showTime(time);
    
                if(time<=0){
                    setTimeout(() => {
                        alert("The order has expired.");
                    }, 0);
                    clearInterval(this.interval);
                    
                    return;
                }
            },1000);
        }
    }

    showTime = (time)=>{
        var minute = Math.floor(time/60);
        var second = time%60;
        minute = minute < 10 ? "0" + minute:minute;
        second = second < 10 ? "0" + second:second;
        var text = minute + ":"+second;
        this.setState({timeText:text});
    }


    requestOrderDetail = ()=>{
        this.setState({
            orderDetail:{
                "goodsName": T.cookie.get('productName')|| "优选人生定期寿险",
                "amount": T.urlQuery('price'),
            }
        })
        return
        T.fetch({
            url:"/order/query/"+ this.orderNo +".json",
            loading:true,
            data:{
                    orderNo: T.urlQuery("id"),
                }
        }).then((result)=>{
            let data = result.value  || { "orderGoodsDTO": {
                "goodsName": "优选人生定期寿险",
                "goodsOutId": "10",
                "copy": "1",
                "amount": "3015.00",
                "reductionAmount": "0.00",
                "orderId": 164007
            }}
            let detail;
            if(data.orderType == 'FAMILY'){
                detail = data.childOrderResponseDTOs[0].orderGoodsDTO ||{};               
            }else {
                detail = data.orderGoodsDTO ||{};               
            }
            detail.amount = data.amount || 0;
            if(T.urlQuery("topup") && detail.amount){
                detail.amount =  + detail.amount + (+T.urlQuery("topup"))
            }
            this.setState({
                orderDetail:detail
            })
        });
    }

    

    confirmToPay = ()=>{
         this.setState({paying:true})
         return;
        
        const orderDetail = this.state.orderDetail
        T.fetch({
            url:"/pay/prePay.json",
            loading:true,
            data:{
                    bizTypeEnum:"MARKETING_ORDER",    //RENEWAL_ORDER_PAY  续期订单支付
                    orderNo: this.orderNo,
                    payPassword: "",
                    balancePayment: 0,
                    cashierPayment: {
                        uniqueNo: this.orderNo,
                        payChannel: "wx_qr",
                        amount: orderDetail.amount,
                        subject:orderDetail.goodsName
                    }
                }
        }).then((result)=>{
            if(result.success){
                let data = result.value;
                this.setState({paying:true})
            }else{
                this.setState({
                    payFailure:true
                })
            }
        });
    }

    payedAction = ()=>{
        T.showLoading()
        setTimeout(() => {
            T.hideLoading()
            actions.routing.push("/success-poc?id="+this.orderNo)
        }, 1500);
        
        return


        this.setState({paying:false})

        T.fetch({
            url:"/pay/paySuccess.json",
            loading:true,
            data:{
                    payMethod:"WeChat_PAY",    //RENEWAL_ORDER_PAY  续期订单支付
                    orderNo: this.orderNo,
                }
        }).then((result)=>{
            if(result.success){
                let data = result.value;
                actions.routing.push("/success-poc?id="+this.orderNo)
            }else{
                this.setState({
                    payFailure:true
                })
            }
        });
    }
    submitPassword = ()=>{		
        this.cancel();
		T.fetch({				
			url:"/customer/check/transactionPwd.json",
			data:{"password":this.state.pwd},
			}).then((res)=>{
			if(res.success){
				    if(res.value)   //交易密码正确 则去支付
					this.confirmToPay();
				}
		});
	}
	cancel =()=>{		
		this.setState({
			show:false
		})
	}
	showModal=()=>{ 
        if(this.state.payFailure){
            this.confirmToPay();
        }else{
            this.setState({
                show:true
            })
        }  
	}
	getPwd=(e)=>{
		this.setState({
			pwd:e
		})
	}
   
	
	render() {
        const orderDetail = this.state.orderDetail;

		return (<div className="surrender-payway"><div className="main bor-top pay" style={{paddingBottom:0}}>
        <div className="clearfix bgfw pt15 pb15 pl30 pr30 f28">
            <p className="fl"><FormattedMessage id='remain_pay_time' defaultMessage='剩余支付時間'/></p>
            <p className="fr"><img src="/assets/images/clock.png" className="mr10 mb5" width="15" height="15"/><span id="timeSpan">{this.state.timeText}</span></p>
        </div>

        <div className="mt30 bgfw pl30 pr30 f28">
            <div className="clearfix pt30 pb30 bor-bottom">
                <p className="fl"><FormattedMessage id='product_name' defaultMessage='產品名稱'/></p>
                <p className="fr">{orderDetail.goodsName}</p>
            </div>
            <div className="clearfix pt30 pb30">
                <p className="fl"><FormattedMessage id='price' defaultMessage='价格'/></p>
                <p className="fr color-price f30 strong">{orderDetail.amount}</p>
            </div>
        </div>

        <div >
            <p className="f30 pt30 pb30 ml30 mr30 strong"><FormattedMessage id='pay_way' defaultMessage='支付方式'/></p>
            <div className="bgfw pl30 pr30" id="payWayChooseBox">
                 <div className="clearfix pt30 pb30 bor-bottom">
                    <p className="fl"><i className=" pay-icon wechat-icon mr30 fl"></i> <span className="fl mt10"><FormattedMessage id='wechat' defaultMessage='微信'/></span></p>
                    <i className="fr choose-box choose choosed-box mt10"></i>
                </div>
                {/* <div className="clearfix pt30 pb30">
                    <p className="fl"><i className=" pay-icon alipay-icon mr30 fl"></i> <span className="fl mt10">支付宝</span></p>
                    <i className="fr choose-box choose mt10"></i>
                </div> */}
            </div>
        </div>

        <div className="footer diy_background-grab pay-btn tac f30 fcw pt30" onClick={this.confirmToPay}>
        <FormattedMessage id='pay_now' defaultMessage='立即支付'/>
        </div>
    </div>
    

    {this.state.paying &&
        <div className="page-layer" style={{zIndex:99}}>
            <div className="layer-content-wrap-pay">
                <div className="layer-content">
                    <div className="tac pt20 pb10 bor-bottom clearfix pl30 pr30">
                        <p className="fl tal" style={{width:'32%'}}><img onClick={()=>this.setState({paying:false})} src="/assets/images/close1.png" style={{width:'.6rem',height:'.5rem'}}/></p>
                        <p className="f30 fl" style={{width:'33%'}}><FormattedMessage id='pay' defaultMessage='支付'/></p>
                        <p className="fr diy_color-grab f26 tar none" style={{width:'32%'}}>Use Password</p>
                    </div>
                    <div className="declare-p f26 tac">
                        <span className="fc3 f30">{this.state.orderDetail.goodsName}</span>
                        <p className="strong f36 mt10 pb30 bor-bottom">{this.state.orderDetail.amount}</p>
                        <p className="f26  pb20 bor-bottom tal p-relative">
                            <img src="/assets/images/payway-icon.png" style={{height:'.6rem'}} className="mr20"/>Credit Card ( 0835 ) 
                            <i className="icon-right p-absolute" style={{right:0,top:'.1rem'}}></i>
                        </p>
                        <div className="mt30">
                            <div className="page-btn-1 mt10 diy_background-grab" onClick={this.payedAction}><FormattedMessage id='confirm_pay' defaultMessage='確認支付'/></div>
                        </div>
                    </div>
                </div>
            </div>       
        </div>
    }
    
    <PwdModal show={this.state.show} cancel={this.cancel} getPwd={this.getPwd} submitPassword={this.submitPassword}/>
    </div>)
	}
}

export default App;   